package org.jeecg.modules.system.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class DelayApiFilter implements Filter {

	private static List<String> exceptUri = new ArrayList<>();

	@Value("${mesh.apiDelayTime:0}")
	private Integer apiDelayTime;
	@Value("${mesh.loginDelayTime:0}")
	private Integer loginDelayTime;
	@Value("${mesh.specialDelay.time:0}")
	private Integer specialTime;
	@Value("${mesh.specialDelay.urls: null}")
	private String specialUrls;
	static {
		exceptUri.add("/mesh-controller/sm/getSm2PublicKey");
		exceptUri.add("/mesh-controller/sys/logout");
		exceptUri.add("/mesh-controller/sys/permission/getUserPermissionByToken");
		exceptUri.add("/mesh-controller/cas/client/validateLogin");
		exceptUri.add("/mesh-controller/cas/client/getCurrentUserName");
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String url = request.getRequestURI();
		if (url.contains("//")) {
			url = url.replace("//", "/");
		}
		if (!exceptUri.contains(url) && apiDelayTime != null && apiDelayTime > 0) {
			try {
				List<String> specialUrlList = new ArrayList<>();
				if (!"null".equals(specialUrls) && StringUtils.isNotBlank(specialUrls)) {
					String[] urls = specialUrls.split(",");
					for (String urlStr : urls) {
						specialUrlList.add("/mesh-controller" + urlStr);
					}
				}

				if (specialUrlList.contains(url)) {
					log.info(url + " special url delayTime " + specialTime);
					Thread.sleep(specialTime);
				} else {
					log.info(url + " api url delayTime " + apiDelayTime);
					Thread.sleep(apiDelayTime);
				}
			} catch (InterruptedException e) {

			}
		} else {
			try {
				log.info(url + " login url delayTime " + loginDelayTime);
				Thread.sleep(loginDelayTime);
			} catch (InterruptedException e) {

			}
		}

		filterChain.doFilter(servletRequest, servletResponse);
	}

}
